package com.gzw.scm.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.PDAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.PDInfo;
import com.gzw.scm.bean.SCPDInfo;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.List;



/**
 * Created by Administrator on 2017/7/18.
 */

public class PDZZXActivity extends BaseActivity{
    private Toolbar toolbar;
    private Intent intent;
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Button btn_sure;
    private DBManager dbManager;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private List<PDInfo> ls_pdInfo,ls_pd,ls_allpd;
    private PDAdapter pdAdapter;
    private TextView tv_zksl,tv_ypdsl,tv_ycsl,tv_ysmsl,tv_wxsl,tv_bfsl,tv_pysl,tv_pksl;
    private String type;
    private boolean isSelete=false;
    private Logger log;


    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_pd);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        tv_zksl = (TextView)findViewById(R.id.tv_zksl);
        tv_ypdsl = (TextView)findViewById(R.id.tv_ypdsl);
        tv_ycsl = (TextView)findViewById(R.id.tv_cysl);
        tv_wxsl= (TextView)findViewById(R.id.tv_wxsl);
        tv_bfsl= (TextView)findViewById(R.id.tv_bfsl);
        tv_ysmsl= (TextView)findViewById(R.id.tv_ysmsl);
        tv_pysl=(TextView)findViewById(R.id.tv_pysl);
        tv_pksl=(TextView)findViewById(R.id.tv_pksl);

        //初始化 log
        log=Logger.getLogger(this.getClass());
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("盘点");
        setSupportActionBar(toolbar);
        intent = getIntent();
        ls_pdInfo = new ArrayList<>();
        ls_pd= new ArrayList<>();
        ls_allpd= new ArrayList<>();
        dbManager = new DBManager(mContext);
        type="0";

        /**
         * 刷新框架
         * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        setStartData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        tv_zksl.setOnClickListener(new myOnClick());
        tv_bfsl.setOnClickListener(new myOnClick());
        tv_wxsl.setOnClickListener(new myOnClick());
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    if(type.equals("0")){
                     T.showShort(mContext,"请先选择要盘点的类型");
                    }else {
                     sendData();
                    }
                    break;
                case R.id.tv_zksl:
                    type = "1";
                    changeZt(type);
                    break;
                case R.id.tv_wxsl:
                    type = "2";
                    changeZt(type);
                    break;
                case R.id.tv_bfsl:
                    type = "3";
                    changeZt(type);
                    break;
                default:
                    finish();
                    break;//603791598
            }
        }
    }

    private void changeZt(String type){
        isSelete=true;
        setStartData();
        dbManager.deleteAllPDSMInfo(MyApplication.getUserInfo().getDid());
        dbManager.deleteAllPDInfo(MyApplication.getUserInfo().getDid());
        dbManager.deleteAllMPDInfo(MyApplication.getUserInfo().getDid());
        getPdInfo();

        if(type.equals("1")){
            tv_zksl.setTextColor(mContext.getResources().getColor(R.color.orange));
            tv_wxsl.setTextColor(mContext.getResources().getColor(R.color.black));
            tv_bfsl.setTextColor(mContext.getResources().getColor(R.color.black));

        }else if(type.equals("2")){
            tv_zksl.setTextColor(mContext.getResources().getColor(R.color.black));
            tv_wxsl.setTextColor(mContext.getResources().getColor(R.color.orange));
            tv_bfsl.setTextColor(mContext.getResources().getColor(R.color.black));

        }else if(type.equals("3")){
            tv_zksl.setTextColor(mContext.getResources().getColor(R.color.black));
            tv_wxsl.setTextColor(mContext.getResources().getColor(R.color.black));
            tv_bfsl.setTextColor(mContext.getResources().getColor(R.color.orange));
        }

        GetPdInfoTask getPdInfoTask = new GetPdInfoTask();
        getPdInfoTask.execute(type);
    }


    private void setStartData(){
        tv_zksl.setText("可用数量:0");
        tv_ysmsl.setText("已扫描数量:0");
        tv_ypdsl.setText("已盘点数量:0");
        tv_ycsl.setText("差异数量:0");
        tv_bfsl.setText("报废数量:0");
        tv_wxsl.setText("维修数量:0");
        tv_pysl.setText("盘盈数量:0");
        tv_pksl.setText("盘亏数量:0");

    }

    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        if(code.contains("该二维码不是周转箱")){
            T.showShort(mContext,"该二维码不是周转箱");
        }else {
            if(isSelete){
             isScan(code);
            }else{
             T.showShort(mContext,"请先选择要盘点的类型");
            }
        }
        return code;
    }


    /**
     * 判断扫描信息
     * */

    private void isScan(String code) {
        List<PDInfo> ls_pdInfo=dbManager.SelectPDInfo(MyApplication.getUserInfo().getDid());

        if (dbManager.IsExistPDSMbh(code, MyApplication.getUserInfo().getDid()) == true) {
            T.showShort(mContext, "该周转箱编号已扫描");
            return;
        }else if(dbManager.IsExistMPDSMbh(code, MyApplication.getUserInfo().getDid()) == true){
            T.showShort(mContext, "该周转箱编号已扫描");
            return;
        }
        else {
            if(dbManager.IsExistPDbh(code, MyApplication.getUserInfo().getDid()) == false){
                dbManager.addMPdsminfo(code, MyApplication.getUserInfo().getDid());
            }else{
                dbManager.addPdsminfo(code, MyApplication.getUserInfo().getDid());
            }
            PDInfo pdInfo = new PDInfo();
            pdInfo.setZt("1");
            pdInfo.setBh(code);
            for(int i=0;i<ls_pd.size();i++) {
                if (ls_pd.get(i).getBh().equals(code)) {
                    ls_pd.remove(i);
                    ls_pd.add(0, pdInfo);
                    break;
                }
            }


            if(!ls_pd.contains(pdInfo)){
              ls_pd.add(0, pdInfo);
            }
            setData();
        }
    }
    /**
     * 获取盘点信息
     * */
    private void getPdInfo(){
        ls_pd.clear();
        ls_pd=dbManager.SelectPDInfo(MyApplication.getUserInfo().getDid());
        setData();
    }

    /**
     * 盘点信息显示
     * */
    private void setData(){
        List<SCPDInfo> ls_sm=dbManager.SelectPDSMInfo(MyApplication.getUserInfo().getDid());
        List<SCPDInfo> ls_sm1=dbManager.SelectMPDSMInfo(MyApplication.getUserInfo().getDid());

        tv_ysmsl.setText("已扫描数量:"+String.valueOf(ls_sm.size()+ls_sm1.size()));

        ls_allpd.clear();
        ls_allpd.addAll(ls_pd);
        if (mRecyclerView.getAdapter() == null) {
            pdAdapter = new PDAdapter(ls_allpd,mContext);
            mRecyclerView.setAdapter(pdAdapter);
        } else {
            pdAdapter.notifyDataSetChanged();
        }
    }


    class DidInfo{
        private String did;
        private String type;

        public String getDid() {
            return did;
        }

        public void setDid(String did) {
            this.did = did;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }
    }
    /**
     *获取盘点信息返回类
     */
    class SelectInfo{
        private String tboxno;
        private String tboxerm;

        public String getTboxno() {
            return tboxno;
        }

        public void setTboxno(String tboxno) {
            this.tboxno = tboxno;
        }

        public String getTboxerm() {
            return tboxerm;
        }

        public void setTboxerm(String tboxerm) {
            this.tboxerm = tboxerm;
        }
    }

    /**
     * 获取待盘点信息的数据请求
     * */

    public class GetPdInfoTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            DidInfo didInfo = new DidInfo();
            didInfo.setDid(String.valueOf(MyApplication.getUserInfo().getDid()));
            didInfo.setType(params[0]);
            String didstr = JsonUtil.toJson(didInfo);
            String json="json="+didstr;
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pdapd.do", "getTboxsPd"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            try {

            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接异常");
                return;
            }
                if(result.contains("系统异常")){
                    showAlertDialog("网络异常");
                    return;
                }
            List<SelectInfo> ls_info = JsonUtil.getPersons(result, new TypeToken<List<SelectInfo>>() {
            }.getType());

            if(ls_info.size()==0){
                T.showShort(mContext,"暂无盘点信息");
                ls_pd.clear();
                setData();
            }else {
                List<String> ls_bh = new ArrayList<>();
                for(SelectInfo selectInfo:ls_info){
                    ls_bh.add(selectInfo.getTboxno());
                }
                dbManager.addPdinfo(ls_bh,MyApplication.getUserInfo().getDid());
                List<PDInfo> ls_pd1=dbManager.SelectPDInfo(MyApplication.getUserInfo().getDid());
                if(type.equals("1")){
                    tv_zksl.setText("可用数量:"+String.valueOf(ls_pd1.size()));
                    tv_bfsl.setText("报废数量:0");
                    tv_wxsl.setText("维修数量:0");
                }else if(type.equals("3")){
                    tv_zksl.setText("可用数量:0");
                    tv_bfsl.setText("报废数量:"+String.valueOf(ls_pd1.size()));
                    tv_wxsl.setText("维修数量:0");
                }else if(type.equals("2")){
                    tv_zksl.setText("可用数量:0");
                    tv_bfsl.setText("报废数量:0");
                    tv_wxsl.setText("维修数量:"+String.valueOf(ls_pd1.size()));
                }
                getPdInfo();

            }
            }catch (Exception e) {
                log.info("getTboxsPd:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**
     * 上传盘点信息
     * */
    private void sendData(){
        List<PDInfo> ls_pdInfo=dbManager.SelectPDInfo(MyApplication.getUserInfo().getDid());
        List<SCPDInfo> ls_info = dbManager.SelectPDSMInfo(MyApplication.getUserInfo().getDid());
        List<SCPDInfo> ls_sm1=dbManager.SelectMPDSMInfo(MyApplication.getUserInfo().getDid());

        if(ls_info.size()==0&&ls_sm1.size()==0){
            T.showShort(mContext,"请先扫描要盘点的二维码");
            return;
        }else{
            showSCPDInfo(ls_info,ls_sm1,ls_pdInfo);
        }
    }

    /**
     * 上传盘点信息的提示框
     * */
    private void showSCPDInfo(final List<SCPDInfo> ls_info,final List<SCPDInfo> ls_info1,final List<PDInfo> ls_pdInfo){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        int num = ls_info.size()+ls_info1.size();
        builder.setTitle("计划盘点"+ls_pdInfo.size()+"条信息，已盘点"+num+"条信息，确定要上传吗");
        builder.setPositiveButton("确定", (dialog, which) ->  {

                String pdstr = JsonUtil.toJson(ls_info);
                String mstr = JsonUtil.toJson(ls_info1);
                pdstr.replace("/","");
                SendPdInfoTask sendPdInfoTask = new SendPdInfoTask();
                sendPdInfoTask.execute(pdstr,type,mstr);

        });
        builder.setNegativeButton("取消", (dialog, which) -> {
        });
        builder.show();
    }

    /**
     * 上传盘点的类
     * */
    class PandianInfo{
        private String department_id;
        private String userid;
        private String belongId;
        private String type;
        private String dataTableTag;
        private String manyTboxs;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getDepartment_id() {
            return department_id;
        }

        public void setDepartment_id(String department_id) {
            this.department_id = department_id;
        }

        public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getBelongId() {
            return belongId;
        }

        public void setBelongId(String belongId) {
            this.belongId = belongId;
        }

        public String getDataTableTag() {
            return dataTableTag;
        }

        public void setDataTableTag(String dataTableTag) {
            this.dataTableTag = dataTableTag;
        }

        public String getManyTboxs() {
            return manyTboxs;
        }

        public void setManyTboxs(String manyTboxs) {
            this.manyTboxs = manyTboxs;
        }
    }

    /**
     * 上传盘点信息的数据请求
     * */

    public class SendPdInfoTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            PandianInfo pandianInfo = new PandianInfo();
            pandianInfo.setUserid(String.valueOf(MyApplication.getUserInfo().getId()));
            pandianInfo.setBelongId(String.valueOf(MyApplication.getUserInfo().getBelongId()));
            pandianInfo.setDepartment_id(String.valueOf(MyApplication.getUserInfo().getDid()));
            pandianInfo.setType(params[1]);
            pandianInfo.setDataTableTag(params[0]);
            pandianInfo.setManyTboxs(params[2]);
            String str = JsonUtil.toJson(pandianInfo);
            str.replace("\\","");
            String json="json="+str;
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("pdapd.do", "getTboxsPdInfo"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            // {"Result":true,"DataTableTagStatus":
            // [{"map":{},"remark":"RDC盘点成功","status":"0","tagstring":"2017080300000042"},
            // {"map":{},"remark":"RDC盘点成功","status":"0","tagstring":"2017080300000043"},
            // {"map":{},"remark":"RDC盘点成功","status":"0","tagstring":"2017080300000044"}]}

            mProgressDialog.dismiss();

            try{
            if (result == null || result.length() == 0) {
                showAlertDialog("连接异常");
                return;
            }
//{"Result":true,"DataTableTagStatus":[{"remark":"该编号不存在","status":"1","tagstring":"20170517145512582"}]}
            String zt = JsonUtil.getMsg(result, "Result").toString();
            if(zt.equals("false")){
                showAlertDialog("网络异常");
            }else if(result.contains("该编号不存在")){
                showAlertDialog("该编号不存在");
            }else{
                String str = JsonUtil.getMsg(result,"DataTableTagStatus").toString();
                String ypdsl= JsonUtil.getMsg(result,"fcount").toString();
                String ycsl= JsonUtil.getMsg(result,"dcount").toString();
                String ysmsl = JsonUtil.getMsg(result,"count").toString();
                String pysl = JsonUtil.getMsg(result,"pycount").toString();
                String pksl = JsonUtil.getMsg(result,"pkcount").toString();

                tv_ysmsl.setText("已扫描数量:"+ysmsl);
                tv_ypdsl.setText("已盘点数量:"+ypdsl);
                tv_ycsl.setText("差异数量:"+ycsl);
                tv_pysl.setText("盘盈数量:"+pysl);
                tv_pksl.setText("盘亏数量:"+pksl);


                List<JgInfo> ls_info = JsonUtil.getPersons(str, new TypeToken<List<JgInfo>>() {
                }.getType());
                for(int i=0;i<ls_info.size();i++){
                    if(ls_info.get(i).getStatus().equals("0")){
                        dbManager.deletePDInfo(MyApplication.getUserInfo().getDid(),ls_info.get(i).getTagstring());
                        dbManager.deletePDSMInfo(MyApplication.getUserInfo().getDid(),ls_info.get(i).getTagstring());
                    }
                }
//                dbManager.deleteAllMInfo(MyApplication.getUserInfo().getDid());
//                getPdInfo();

                List<PDInfo> ls_pdInfo=dbManager.SelectPDInfo(MyApplication.getUserInfo().getDid());
                if(ls_pdInfo.size()==0){
                    showAlertDialog("盘点成功");
                }else{
                    showAlertDialog(ls_pdInfo.size()+"条未盘点");
                }
                dbManager.deleteAllPDSMInfo(MyApplication.getUserInfo().getDid());
                dbManager.deleteAllPDInfo(MyApplication.getUserInfo().getDid());
                dbManager.deleteAllMPDInfo(MyApplication.getUserInfo().getDid());
                getPdInfo();
                type="0";
                isSelete=false;
            }
            }catch (Exception e) {
                log.info("getTboxsPdInfo:"+e.toString()+"/result="+result);
                e.printStackTrace();
                showAlertDialog(e.toString());
            }
        }
    }

    /**
     * 上传盘点信息返回类
     * */
    class JgInfo{
        private String remark;
        private String status;
        private String tagstring;

        public String getRemark() {
            return remark;
        }

        public void setRemark(String remark) {
            this.remark = remark;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getTagstring() {
            return tagstring;
        }

        public void setTagstring(String tagstring) {
            this.tagstring = tagstring;
        }
    }
}
